package com.jc.service.task.store;

import com.alibaba.fastjson.JSONObject;
import com.jc.common.util.*;
import com.jc.ds.model.Supplier;
import com.jc.framework.enums.ThirdPartyParam;
import com.jc.service.h5.ShopService;
import com.jc.service.supplier.SupplierService;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.*;

@SuppressWarnings("all")
@Service
public class StoreServiceImpl implements StoreService {

    private Long ts = new Date().getTime();
    public Logger getLoger() {
        return LoggerFactory.getLogger(this.getClass());
    }

    @Autowired
    private SupplierService supplierService;
    @Autowired
    private ShopService shopService;

    @Transactional
    @Override
    public Map<String,Object> synStore() throws IOException, URISyntaxException {
        Map<String,Object> resultMap = new HashMap<>();

        Map<String,Object> param = new HashMap<>();
        param.put("code",shopService.getShopConfig().getCODE());
        param.put("encryptedString", MD5.passmd5("code="+shopService.getShopConfig().getCODE()+"&ts="+String.valueOf(ts)+"&key="+shopService.getShopConfig().getKEY()));
        param.put("ts",ts);
        resultMap.put("param",param);
        //请求第三方接口 获取商家列表
        String res = HttpUtil.get(shopService.getShopConfig().getURL()+ThirdPartyParam.STORE_URL.getName(), param);
        resultMap.put("resultText",res);
        Map<String,Object> resMap = JSONObject.parseObject(res, Map.class);
        if (resMap.get("returnCode").equals(1)){
            return resultMap;
        }
        List<Map<String,Object>> stores = (List<Map<String, Object>>) resMap.get("list");
        stores.forEach(store->{
            //判断数据库中是否存在 不存在新增 存在更新
            Supplier supplier = new Supplier();
            supplier.setSupplierSn(String.valueOf(store.get("id")));
            List<Supplier> suppliers = supplierService.queryAll(supplier);
            if (CollectionUtils.isNotEmpty(suppliers)){
                //不为空 更新
                supplier.setSimpleName(String.valueOf(store.get("name")));
                supplier.setFullName(String.valueOf(store.get("name")));
                supplier.setId(suppliers.get(0).getId());
                supplier.setEditTime(new Date());
                supplierService.modify(supplier,false);
            }else{
                //新增
                supplier.setSimpleName(String.valueOf(store.get("name")));
                supplier.setFullName(String.valueOf(store.get("name")));
                supplier.setCreateTime(new Date());
                supplierService.add(supplier,false);
            }
        });
        return resultMap;
    }
}
